package com.df.resources.listener;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.df.resources.common.GatewayInstancesManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;


@ConditionalOnBean(NamingService.class)
@Component
public class GatewayInstanceListener {

    @Autowired
    NamingService namingService;

    @Value("${gateway-server.name}")
    String gatewayServerName;

    @PostConstruct
    public void addListener() throws NacosException {
        if(gatewayServerName.isEmpty()){
            throw new RuntimeException("网关服务名为空，无法添加监听器");
        }
        namingService.subscribe(gatewayServerName,event -> {
            NamingEvent namingEvent= (NamingEvent) event;
            List<Instance> instances = namingEvent.getInstances();
            GatewayInstancesManager.updateInstance(instances);
        });
    }

    @PreDestroy
    public void removeListenr() throws NacosException {
        namingService.unsubscribe(gatewayServerName,event -> {
            System.out.println("gatewayInstance listener removed");
        });
    }
}
